package com.chenchao.web;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/26 15:12
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.web.Test.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 手写web容器
 */
public class Test01 {
    public static void main(String[] args) throws IOException {
        while (true){
            /*获取请求后开启新的线程*/
            Socket accept = WebTest.serverSocket.accept();
            Thread thread = new Thread(new WebTest(accept));
            thread.start();
        }
    }
}

class WebTest implements Runnable{
    /**Css样式后缀*/
    public static final String TYPE_CSS="css";
    static ServerSocket serverSocket;
    private Socket accept;
    /**默认文件后缀*/
    private String suffix="Content-Type:text/html";

    static {
        try {
            serverSocket = new ServerSocket(10000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public WebTest() {
    }

    public WebTest(Socket accept) {
        this.accept = accept;
    }

    /**
     * 处理一个请求
     */
    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(accept.getInputStream()));
            /*获取请求字符串的请求头*/
            String str=br.readLine();
            if(str==null){
                return;
            }
            /*解析字符串*/
            File file = resolveStr(str);
            /*写回文件*/
            sendFile(file);
            br.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 解析收到的字符串请求，并返回请求的文件对象
     * @param str 收到的字符串请求
     * @return 请求的文件对象
     */
    public File resolveStr(String str) {
        System.out.println("收到的字符串" + str);
        String s = str.split(" ")[1];
        File file = new File(s.substring(1));
        /*获取第二个字段访问信息*/

        /*获取文件后缀以判断文件类型*/
        String[] split = s.split("\\.");
        /*或｜，点.，加+，乘* 分割字符串时需要转义*/
        if(split.length>0&&TYPE_CSS.equals(split[split.length - 1])){
            suffix="Content-Type:text/css";
        }

        if (file.exists()) {
            System.out.println("文件存在");
            return file;
        }
        System.out.println("文件不存在");
        return null;
    }

    /**
     * 向浏览器发送其请求的文件
     * @param file 浏览器请求的文件
     * @throws IOException IOException
     */
    public void sendFile(File file) throws IOException {
        OutputStream outputStream = accept.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

        /*写回响应头，200表示正常*/
        writer.write("HTTP/1.1 200 OK");
        writer.newLine();
        /*写回文件类型*/
        writer.write(suffix);
        writer.newLine();
        /*文档分割空行，不然浏览器不解析内容*/
        writer.newLine();
        /*把文件写回*/
        writer.flush();
        /*使用缓存流一定要在这里刷新一下,不然后面的流会先输出，导致浏览器解析错误*/

        /*传送文件*/
        if (file != null) {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            System.out.println("文件发送成功");
            bis.close();
        }

        /*关闭资源*/
        accept.close();
    }


}
